package com.nowcoder.Offer.Tree;

import org.junit.Test;

/**
 * 序列化二叉树
 */
public class SerializeTree {
    /**
     * 序列化
     */
    String Serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        if(root == null){
            sb.append("#,");
            return sb.toString();
        }
        sb.append(root.val + ",");
        sb.append(Serialize(root.left));
        sb.append(Serialize(root.right));
        return sb.toString();
    }

    public int index = -1;
    /**
     * 反序列化
     */
    TreeNode Deserialize(String str) {
        index++;
        int len = str.length();
        if(index >= len)
            return null;
        String[] strs = str.split(",");

        TreeNode node = null;

        if(!strs[index].equals("#")){
            node = new TreeNode(Integer.valueOf(strs[index]));
            node.left = Deserialize(str);
            node.right = Deserialize(str);
        }
        return node;
    }

    public void inOrder(TreeNode root){
        if(root == null) return;
        inOrder(root.left);

        System.out.print(root.val+" ");

        inOrder(root.right);
    }

    @Test
    public void test(){
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        TreeNode node6 = new TreeNode(6);
        TreeNode node7 = new TreeNode(7);

        node1.left = node2; node1.right = node3;
        node2.left = node4; node2.right = node5;
        node3.left = node6; node3.right = node7;

        String sb = Serialize(node1);
        System.out.println(sb);
    }
}
